<template>
    <view class="face-info-content">

        <view class="face-info-form">
            <up-cell-group>
                <!-- @click="uploadAvatar = true && isEdit" -->
                <up-cell title="人脸上传">
                    <template #label>
                        <view class="upload-content mt-[10rpx]">
                            <up-upload :fileList="faceInfo.face_photo_url" @afterRead="afterRead" @delete="deletePic"
                                name="1" multiple :maxCount="1" :previewFullImage="true" uploadText="选择照片"
                                :disabled="!isEdit"></up-upload>

                            <up-text color="#696969" size="24rpx" text="仅用于园区人脸识别门禁系统，不能带帽饰拍照"></up-text>
                            <text class="mt-[20rpx] text-[#333] text-[24rpx] inline-block">错误示例</text>

                            <view class="w-[90%] face-error-image">
                                <img :src="faceErrorImage" class="w-[100%] h-[215rpx] block" />
                            </view>
                        </view>
                    </template>
                </up-cell>
                <up-cell title="身份证">
                    <template #value>
                        <text v-if="!isEdit">{{ faceInfo.id_card || '未填写' }}</text>
                        <up-input v-else v-model.trim="faceInfo.id_card" type="number" border="none" inputAlign="right"
                            placeholder="请填写身份证"></up-input>
                    </template>
                </up-cell>
                <up-cell>
                    <template #title>
                        <up-text color="#696969" text="仅用于园区人脸识别门禁系统"></up-text>
                    </template>
                </up-cell>
            </up-cell-group>
        </view>

        <view class="operatin-btn">
            <up-button type="primary" v-if="!isEdit" size="large" shape="circle"
                @click="handleEdit">修改</up-button>
            <up-button color="#eb8a1d" v-if="isEdit"  size="large" shape="circle"
                @click="hadnleSave" :loading="loading" loading-text="保存中...">
                保存
            </up-button>
        </view>

        <!-- 消息提醒 -->
        <up-toast ref="uToastRef"></up-toast>
    </view>
</template>

<script>
import { getFaceInfo, updateFaceInfo } from '@/api/faceinfo.js'
import faceErrorImage from '../../static/images/face_error_image.png';
export default {
    data() {
        return {
            faceErrorImage,
            isEdit: false,
            loading: false,
            faceInfo: {
                face_photo_url: [],
                id_card: ''
            }
        }
    },
    computed: {
    },
    created() {
        this.getFaceinfos();
    },
    methods: {
        async getFaceinfos() {
            try {
                const res = await getFaceInfo();
                if (res.code === 2000) {
                    this.faceInfo = res.data;
                    this.faceInfo.face_photo_url = res.data.face_photo_url !== null
                        ? [{ url: res.data.face_photo_url }]
                        : [];
                    // if (res.data.face_photo_url !== null) {
                    //     uni.downloadFile({
                    //         url: this.faceInfo.face_photo_url[0].url,
                    //         success: (success) => {
                    //             this.faceInfo.face_photo_url = [{ url: success.tempFilePath }]
                    //         },
                    //     })
                    // } else {
                    //     this.faceInfo.face_photo_url = []
                    // }
                }
            } catch (error) {
                console.log(error);
            }
        },
        handleEdit() {
            this.isEdit = true;
            this.$refs.uToastRef.show({
                type: 'default',
                message: "开始编辑",
                duration: 1000
            })
        },
        async hadnleSave() {
            if (this.loading) {
                this.$refs.uToastRef.show({
                    type: 'default',
                    message: "正在处理，请稍候...",
                    duration: 1000
                });
                return;
            }
            this.loading = true;
            try {
                this.checkSave();
                if (this.faceInfo.face_photo_url.length === 0) {
                    throw new Error("No face photo uploaded");
                }


                const filePath = this.faceInfo.face_photo_url[0].size
                    ? this.faceInfo.face_photo_url[0].url
                    : await uni.downloadFile({url: this.faceInfo.face_photo_url[0].url});
                const file = typeof filePath === 'string' ? filePath : filePath.tempFilePath;
                uni.uploadFile({
                    url: '/system/user/update_identity/', // 替换为你的真实接口地址
                    filePath: file,
                    name: 'face_photo',
                    formData: {
                        id_card: this.faceInfo.id_card
                    },
                    success: (uploadFileRes) => {
                        this.$refs.uToastRef.show({
                            type: 'success',
                            message: JSON.parse(uploadFileRes.data).msg
                        });
                    },
                    fail: (err) => {
                        console.error('上传失败:', err);
                        this.$refs.uToastRef.show({
                            type: 'error',
                            message: '上传失败，请重试'
                        });
                    }
                });
            } catch (error) {
                console.error('错误:', error);
                this.$refs.uToastRef.show({
                    type: 'error',
                    message: error.message || '未知错误'
                });
            } finally {
                this.loading = false;
                this.isEdit = false;
            }
        },
        /* 校验 */
        checkSave() {
            const idCardPattern = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/;
            if (this.faceInfo.face_photo_url.length == 0) {
                this.$refs.uToastRef.show({
                    type: 'default',
                    message: "上传人脸图片"
                });
                return;
            }
            if (!this.faceInfo.id_card || !idCardPattern.test(this.faceInfo.id_card)) {
                this.$refs.uToastRef.show({
                    type: 'default',
                    message: "请填写有效的18位身份证号"
                });
                return;
            }
        },
        async afterRead(event) {
            this.faceInfo.face_photo_url = event.file;
            // this.loading = true;
            // uni.uploadFile({
            //     url: '/system/upload/file/', // 替换为你的真实接口地址
            //     filePath: event.file[0].url,
            //     name: 'file',
            //     header: {
            //         'Content-Type': 'multipart/form-data' // 根据需要设置请求头
            //     },
            //     success: (uploadFileRes) => {
            //         console.log(JSON.parse(uploadFileRes.data));
            //         this.faceInfo.face_photo_url = [JSON.parse(uploadFileRes.data).data];
            //         this.$refs.uToastRef.show({
            //             type: 'success',
            //             message: '人脸信息上传成功'
            //         })
            //         this.loading = false;
            //         console.log(this.faceInfo.face_photo_url[0].url);
            //     },
            //     fail: (err) => {
            //         console.error('上传失败:', err);
            //         this.loading = false;
            //     }
            // })
        },
        deletePic(event) {
            if (!this.isEdit) return;
            this.faceInfo.face_photo_url.splice(event.index, 1)
        },
        handleErrors(errorData) {
            if (errorData) {
                for (const key in errorData) {
                    if (errorData.hasOwnProperty(key)) {
                        const errorMessages = errorData[key];
                        if (Array.isArray(errorMessages)) {
                            errorMessages.forEach((message) => {
                                // 这里可以使用 uni.showToast 或其他方式展示错误信息
                                uni.showToast({
                                    title: `${key}: ${message}`,
                                    icon: 'none',
                                    duration: 2000
                                });
                            });
                        }
                    }
                }
            } else {
                console.error('未知错误:', errorData);
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.face-info-content {
    width: 100%;
    min-height: 100vh;
    background: #f2f2f2;
    position: relative;
}

.face-info-form {
    background: #ffffff;
}

.operatin-btn {
    position: fixed;
    bottom: 20rpx;
    left: 0;
    right: 0;
    z-index: 999;
    padding: 0 30rpx;
}

.face-error-image {
    margin: 0 auto;
    margin-top: 10rpx;
    margin-bottom: 20rpx;
}
</style>